package com.web.music.portal.mvc;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.web.music.interfaces.UserService;
import com.web.music.model.RegisterForm;

public class RegisterFormValidator implements Validator {
	
	private UserService userService;

	public boolean supports(Class givenClass) {
		return givenClass.equals(RegisterForm.class);
	}

	public void validate(Object obj, Errors errors) {
		RegisterForm form = (RegisterForm) obj;
		if (form == null) {
			errors.reject("error.nullpointer", "Null data received");
		} else {
			if ("".equals(form.getLogin())) {
				errors.rejectValue("login", "error.empty", "Login is required!"); 
			}
			if (userService.existsLogin(form.getLogin())) {
				errors.rejectValue("login", "login.exists", "This login name alredy exists!");
			}
			if (! form.getPassword().equals(form.getRepeatpassw())) {
				errors.rejectValue("password", "password.notmatch", "Passwords don't match!");
				errors.rejectValue("repeatpassw", "password.notmatch", "Passwords don't match!");
			}
		}
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
